package com.xgit.iov.common.core.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgit.iov.common.core.constant.CacheConstants;
import com.xgit.iov.common.core.entity.BaseEntity;
import com.xgit.iov.common.core.entity.IovUser;
import com.xgit.iov.common.core.entity.SysDataRule;
import com.xgit.iov.common.core.feign.RemoteUserService;
import com.xgit.iov.common.core.service.ISuperService;
import com.xgit.iov.common.core.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.util.List;

@Slf4j
public class SuperServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> extends ServiceImpl<M, T> implements ISuperService<T> {

	@Autowired
	private RemoteUserService remoteUserService;

	@Autowired
	private CacheManager cacheManager;

    @Override
    public void dataRuleFilter(T entity) {
		IovUser iovUser = SecurityUtils.getUser();
		entity.setCurrentUser(iovUser);
		if(iovUser == null || (iovUser != null && iovUser.isAdmin())){
			return;
		}
		List<SysDataRule> dataRuleList = null;
		Cache cache = cacheManager.getCache(CacheConstants.DATARULE_DETAILS);
		if (cache != null && cache.get(CacheConstants.DATARULE+iovUser.getId()) != null){
			dataRuleList = (List<SysDataRule>)cache.get(CacheConstants.DATARULE+iovUser.getId()).get();
		} else {
			if (ObjectUtil.isNotNull(remoteUserService.getDataRule())){
				dataRuleList = remoteUserService.getDataRule().getData();
				cache.put(CacheConstants.DATARULE+iovUser.getId(), dataRuleList);
			}

		}

		// 如果是超级管理员，则不过滤数据
		if (ObjectUtil.isNull(dataRuleList) || dataRuleList.size() == 0) {
			return;
		}

		// 数据范围
		StringBuilder sqlString = new StringBuilder();

		for(SysDataRule dataRule : dataRuleList){
			if(entity.getClass().getSimpleName().equals(dataRule.getClassName())){
				sqlString.append(dataRule.getDataScopeSql());
			}

		}

		entity.setDataScope(sqlString.toString());
    }

}
